<script setup lang="ts">
import { computed, ref, type Ref, watch } from "vue";
import { useAppStoreHook } from "@/store/modules/app";
import {
  delay,
  type EchartOptions,
  useDark,
  useECharts,
} from "@pureadmin/utils";
import { apiAccessRank } from "@/api/log";

const { isDark } = useDark();

const theme: EchartOptions["theme"] = computed(() => {
  return isDark.value ? "dark" : "light";
});

const lineChartRef = ref<HTMLDivElement | null>(null);
const { setOptions, resize } = useECharts(lineChartRef as Ref<HTMLDivElement>, {
  theme,
});

const dataSuccessName = ref<string[]>([]);
const dataSuccessCount = ref<number[]>([]);
const dataFailName = ref<string[]>([]);
const dataFailCount = ref<number[]>([]);

function init() {
  setOptions({
    tooltip: {
      trigger: "axis",
      axisPointer: {
        type: "line",
      },
    },
    legend: {},
    grid: {
      containLabel: true,
      top: "10px",
      bottom: "0",
      left: "0",
      right: "0",
    },
    xAxis: [
      {
        type: "category",
        axisLabel: {
          interval: 0,
          rotate: 20,
        },
        axisLine: {
          lineStyle: {
            color: "green",
          },
        },
        data: dataSuccessName.value,
      },
      {
        type: "category",
        axisLabel: {
          interval: 0,
          rotate: 20,
        },
        axisLine: {
          lineStyle: {
            color: "red",
          },
        },
        data: dataFailName.value,
      },
    ],
    yAxis: [
      {
        name: "成功",
        type: "value",
        triggerEvent: true,
      },
      {
        name: "失败",
        type: "value",
        triggerEvent: true,
      },
    ],
    series: [
      {
        name: "成功",
        data: dataSuccessCount.value,
        type: "line",
        lineStyle: {
          color: "green",
        },
        xAxisIndex: 0,
        yAxisIndex: 0,
        emphasis: {
          focus: "series",
        },
      },
      {
        name: "失败",
        data: dataFailCount.value,
        type: "line",
        lineStyle: {
          color: "red",
        },
        xAxisIndex: 1,
        yAxisIndex: 1,
        emphasis: {
          focus: "series",
        },
      },
    ],
    addTooltip: true,
  });
}

apiAccessRank().then(res => {
  res.forEach(chart => {
    if ("成功" === chart.ext) {
      dataSuccessName.value.push(chart.name);
      dataSuccessCount.value.push(chart.count);
    } else {
      dataFailName.value.push(chart.name);
      dataFailCount.value.push(chart.count);
    }
  });
  init();
});

watch(
  () => useAppStoreHook().getSidebarStatus,
  () => {
    delay(600).then(() => resize());
  }
);
</script>

<template>
  <div ref="lineChartRef" style="width: 100%; height: 35vh" />
</template>
